<template>
  <div class="evaluate-detail">
    <el-page-header @back="$router.push('/evaluate/manage/auth')" content="权限审计详情"> </el-page-header>
    <div class="sec-detail-main">
      <!-- 基本信息 -->
      <secAuthBaseInfo :data="contentData" :isEdit="false"></secAuthBaseInfo>
      <!-- 审计进度 -->
      <div class="cls title">审计进度</div>
      <el-steps :active="active" finish-status="success">
        <el-step v-for="(item, index) in steps" :key="index" :title="item.statusName">
          <template slot="description">
            <div>
              <span v-if="item.operaUser">操作人:{{ item.operaUser }}</span
              ><br />
              <span v-if="item.time">操作时间：:{{ item.time }}</span>
            </div>
          </template>
        </el-step>
      </el-steps>
      <!-- 审计结果 -->
      <el-tabs v-model="tabName">
        <el-tab-pane label="审计结果" name="审计结果">
          <sec-table
            :cellClassName="cellClassName"
            :loading="evalResult.loading"
            :optionData="evalResult.optionData"
            :tableData="evalResult.rows"
            :colType="evalResult.colType"
            :disabledProp="evalResult.disabledProp"
            :tableCol="auditResultCol"
          >
            <template v-slot:relScene="{ data }">
              <span v-if="!(data.row.relScene && data.row.relScene.length > 0)">
                <el-tag :type="data.row.status == '-1' ? 'info' : ''">通用场景</el-tag>
              </span>
              <span v-else>
                <el-tag
                  v-for="(item, index) in data.row.relScene"
                  :type="data.row.status == '-1' ? 'info' : ''"
                  :key="index"
                  style="margin: 4px"
                >
                  {{ item }}
                </el-tag>
              </span>
            </template>
            <template v-slot:evidence="{ data }">
              <secUploadImg type="upm" :row="data.row" @uploadSuccess="save(true)"></secUploadImg>
            </template>
          </sec-table>
        </el-tab-pane>
        <el-tab-pane label="风险列表" name="风险列表" :disabled="!tabDisabled.includes(progressData.status)">
          <sec-table :tableData="riskListTableData" :tableCol="riskListCol"></sec-table>
          <div
            style="text-align: center; margin-top: 15px"
            v-if="progressData.recification !== '2' && progressData.admin === '1' && progressData.status === '24'"
          >
            <el-button type="primary" @click="setRiskSoc">同步漏洞平台并生成报告</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
      <div
        class="submit-box"
        style="text-align: center; margin: 20px 0"
        v-if="
          progressData.status !== '36' &&
          progressData.status !== '37' &&
          progressData.status !== '50' &&
          progressData.admin === '1'
        "
      >
        <el-button type="primary" @click="save" v-if="!saveBtnShowStatus.includes(progressData.status)"
          >保 存</el-button
        >
        <el-button
          type="primary"
          v-if="subBtnShowStatus.includes(progressData.status) && progressData.taskStatus === '30'"
          @click="saveAndSubmit"
        >
          提交结果
        </el-button>
        <el-button
          type="primary"
          v-if="accomplishBtnShowStatus.includes(progressData.status) && progressData.recification == '2'"
          @click="saveAndSubmit"
          >完成审计</el-button
        >
      </div>
    </div>
    <el-dialog title="人工忽略" :visible.sync="ignoreDiaShow" width="50%">
      <sec-form ref="ignoreRef" :rules="ignoreRules" :ruleForm="ignoreData" :formData="ignoreFormData"></sec-form>
    </el-dialog>
  </div>
</template>

<script>
import secTags from "components/secTags.vue";
import secAuthBaseInfo from "@/views/propertyCenter/authManage/components/baseInfo.vue";
import { upmReportDetailApi, upmReportItemsApi, upmAssetDetailApi, upmSaveOrSubmitApi } from "api/authApi";
import { riskListApi, riskSocApi, riskMisreportApi, riskHoleStatusApi, riskLevelSaveApi } from "api/controlApi";
import secUploadImg from "../components/uploadImg.vue";
export default {
  name: "evaluateDetail",
  mixins: [],
  props: {
    pageType: String,
  },
  components: {
    secTags,
    secUploadImg,
    secAuthBaseInfo,
  },
  data() {
    return {
      ignoreDiaShow: false,
      selectIndexRow: {}, //点击url列表时存储的行的数据
      evalResultColDisStatus: ["13"], //审计结果tab界面 审计结果之后再审计确认（状态码是13）可操作，其他状态都是置灰
      saveBtnShowStatus: ["24", "25"], //保存按钮展示的审计进度状态码(!非的状态)
      subBtnShowStatus: ["10", "12", "13"], //提交结果按钮展示的审计进度状态码
      accomplishBtnShowStatus: ["24", "25"], //完成审计按钮展示的审计进度状态码
      selectRisk: {},
      tabName: "审计结果",
      active: 1,
      query: {},
      progressData: {}, //审计进度数据
      tabDisabled: ["24", "25", "36", "37", "50"], //风险列表展示
      contentData: {}, //基本信息数据
      steps: [],
      //审计结果数据
      evalResult: {
        //列的类型
        loading: false,
        disabledProp: {
          status: true,
          finalStatus: true,
        },
        colType: {
          riskLevel: "select",
          pocRiskLevel: "select",
          remark: "textarea",
          status: "select",
        },
        optionData: {
          pocRiskLevel: this.$store.state.dictionary.level,
          status: this.$store.state.dictionary.status,
        },
        rows: [],
      },

      //风险列表
      riskListTableData: [],
      //人工忽略
      ignoreData: { remark: "" },
      ignoreRules: {
        remark: [{ required: true, message: this.config.input, trigger: "blur" }],
      },
    };
  },
  computed: {},
  created() {
    //基本信息
    this.baseInfoCol = [
      { label: "资产来源", prop: "source" },
      { label: "资产ID", prop: "id" },
      { label: "appID", prop: "assetCode" },
      { label: "appID域名", prop: "domain" },
      { label: "系统名称", prop: "assetName" },
      {
        label: "资产状态",
        prop: "status",
        formatter: (data) => {
          return this.utils.getDicLabel("100500", data.status);
        },
      },
      //权属信息
      { label: "权属负责人", prop: "leader" },
      { label: "权属部门", prop: "dept2", span: 2 },
      {
        label: "关注人",
        prop: "noticeUsers",
        type: "select",
        multiple: true,
        filterable: true,
        remote: true,
        optionProps: { label: "name", value: "account" },
        remoteMethod: (query) => {
          this.loadingProp.noticeUsers = true;
          userApi({ account: query }).then((res) => {
            this.loadingProp.noticeUsers = false;
            this.optionData.noticeUsers = res.data;
          });
        },
        span: 1,
      },
      { label: "创建人", prop: "Users", span: 2 },
      { type: "slot", label: "git地址", prop: "gitList", span: 3 },
      { label: "备注", prop: "remark1", type: "textarea", contentStyle: "width:50%", span: 3 },
    ];
    //审计结果表头
    let imgUploadCol = [{ label: "材料上传", prop: "evidence", type: "slot", width: 300, align: "left" }];
    //权限快捷审计详情，审计结果 现状描述和审计结果只读模式。材料生产列去掉
    if (this.pageType === "upm_auth_quick") {
      imgUploadCol = [];
      this.evalResult.colType.status = "";
      this.evalResult.colType.remark = "";
    }
    this.auditResultCol = [
      { label: "指标名称", prop: "name", align: "left" },
      { label: "指标要求", prop: "reportItemContent", align: "left", width: 300 },
      { label: "关联场景", prop: "relScene", type: "slot", align: "left" },
      {
        label: "现状描述",
        maxlength: 500,
        prop: "remark",
        maxlength: 500,
        width: 300,
        blur: () => {
          this.getAdminAuth() && this.save();
        },
      },
      ...imgUploadCol,
      {
        label: "审计结果",
        prop: "status",
        width: 200,
        change: () => {
          this.getAdminAuth() && this.save(true);
        },
        formatter: (row, column, cellValue, index) => {
          if (!this.getAdminAuth()) {
            return this.utils.getDicLabel("status", cellValue);
          }
        },
      },
    ];
    //风险列表表头
    this.riskListCol = [
      // { label: "风险ID", prop: "id", width: 80 },
      { label: "风险名称", prop: "riskName", width: 250, align: "left" },
      { label: "风险描述", prop: "holeDetail", width: 300, align: "left" },
      { label: "修复建议", prop: "repairRecommend", width: 300, align: "left" },

      {
        width: 150,
        label: "风险等级",
        prop: "level",
        change: ($event, { row }) => {
          riskLevelSaveApi({ id: row.id, level: row.level }).then((res) => {
            this.message.state(res);
          });
        },
        optionData: this.$store.state.dictionary.level,
        type: "select",
        // formatter: (row, column, cellValue, index) => {
        //   return this.utils.getDicLabel("level", cellValue);
        // },
      },
      { label: "关联指标", prop: "itemName" },
      // { label: "风险类型", prop: "holeType", width: 150 },
      {
        label: "风险状态",
        prop: "status",
        width: 100,
        formatter: (row, column, cellValue, index) => {
          return this.utils.getDicLabel("100700", cellValue);
        },
      },
      { label: "创建时间", prop: "createTimeText", width: 150 },
      {
        label: "操作",
        prop: "operation",
        width: 220,
        children: [
          {
            label: "同步漏洞平台",
            hide: ({ row, column, $index }) => {
              if (this.$common.isPerIgnore(row.status)) {
                return true;
              }
              let arr = ["0"]; //风险状态码
              return !arr.includes(row.status);
            },
            click: ({ row, column, $index }) => {
              // this.holeDiaShow = true;
              this.utils.$confirm({ content: "是否确认同步漏洞平台?" }, () => {
                this.selectRisk = row;
                this.asyncHoleConfirm();
              });
            },
          },
          {
            label: "人工忽略",
            hide: ({ row, column, $index }) => {
              let arr = ["0"];
              return !arr.includes(row.status);
            },
            click: ({ row, column, $index }) => {
              this.ignoreDiaShow = true;
              this.ignoreData.remark = "";
              this.selectRisk = row;
            },
          },
          {
            label: "详情",
            click: ({ row, column, $index }) => {
              this.$router.push({
                path: "/control/risk/detail",
                query: { riskId: row.id, assetId: row.assetId, code: row.code, assetType: row.assetType },
              });
            },
          },
          {
            hide: ({ row, column, $index }) => {
              if (this.$common.isPerIgnore(row.status)) {
                return true;
              }
              let arr = ["1-4", "5"];
              return !arr.includes(row.status);
            },
            label: "同步工单状态",
            click: ({ row, column, $index }) => {
              riskHoleStatusApi({ riskId: row.id, anquanId: row.anquanId }).then((res) => {
                this.message.success({ message: res.msg });
                this.getRiskList();
              });
            },
          },
          {
            hide: ({ row, column, $index }) => {
              if (this.$common.isPerIgnore(row.status)) {
                return true;
              }
              let arr = ["0", "12"];
              return arr.includes(row.status);
            },
            label: "工单详情",
            click: ({ row, column, $index }) => {
              let domain = "http://anquan.didichuxing.com"; //测试的地址是http://anquan-test.didichuxing.com
              window.open(`${domain}/project/portals/pages/hole-detail.html?id=${row.anquanId}`);
            },
          },
        ],
      },
    ];
    //人工忽略 弹框form表单
    this.ignoreFormData = [
      { type: "textarea", label: "备注", prop: "remark" },
      {
        type: "operation",
        style: { "text-align": "right" },
        children: [
          {
            label: "取 消",
            click: () => {
              this.ignoreDiaShow = false;
            },
          },
          {
            label: "确 认",
            type: "primary",

            click: () => {
              if (this.$refs.ignoreRef.submitForm()) {
                this.ignoreRefConfirm();
              }
            },
          },
        ],
      },
    ];
  },
  mounted() {
    this.query = this.$route.query;
    this.initPage(); //初始化界面
  },
  methods: {
    async initPage() {
      console.log("this.evalResult", this.evalResult);
      let reportData = await upmReportDetailApi({ id: this.query.id, assetId: this.query.assetId });
      //为了安全考虑，不能直接在url上修改报告id和资产id（资产id和报告id一定是关联的才可以）
      if (reportData.data) {
        this.tagList = reportData.data.tagList;
        this.setReportDetail(reportData.data); //审计进度数据
        this.getAssetsDetail(); //基本信息数据获取

        this.getReportItems(); //审计结果
        this.getRiskList(); //风险列表
      }
    },
    //@函数功能:审计进度接口数据获取
    getReportDetail() {
      upmReportDetailApi({ id: this.query.id, assetId: this.query.assetId }).then((res) => {
        this.setReportDetail(res.data);
      });
    },
    /**:审计结果*/
    getReportItems() {
      this.evalResult.loading = true;
      upmReportItemsApi({ reportId: this.query.id, assetId: this.query.assetId }).then((res) => {
        this.evalResult.loading = false;
        res.data.forEach((item) => {
          item.disabled = item.status == "-1" ? true : false;
        });
        this.evalResult.rows = res.data;
      });
    },
    /**获取风险列表数据*/
    getRiskList() {
      let { id, assetId } = this.$route.query;
      riskListApi({
        assetType: "UPM",
        // assetCode: [this.query.assetCode],
        relationId: id,
        dateType: ["upm_report"],
      }).then((res) => {
        res.data.forEach((item) => {
          if (item.status != "0") {
            item.disabled = true;
          }
        });
        this.riskListTableData = res.data;
      });
    },
    /**
     * @函数功能:基本信息
     * @参数输入:
     * @函数返回:
     */
    getAssetsDetail() {
      upmAssetDetailApi({ id: this.query.assetId }).then((res) => {
        this.contentData = res.data;
      });
    },

    /**
     * @函数功能:审计进度数据格处理
     * 评估状态(status): 10创建 | 11系统评估 | 12信息补充 | 13评估确认 24漏洞整改 | 25漏洞复核 | 36 已完成 | 47 已归档 | 48 已删除
     */
    setReportDetail(data) {
      console.log("[ data ] >", data);
      console.log("this.evalResult", this.evalResult);
      this.progressData = data;
      this.evalResult.disabledProp.status = !this.evalResultColDisStatus.includes(this.progressData.status);
      //tab切换默认选中的tab页
      this.tabName = this.tabDisabled.includes(this.progressData.status) ? "风险列表" : "审计结果";
      this.setStep();
      //审计结果 现状描述和审计结果能否操作
      if (this.progressData.admin != "1") {
        this.evalResult.colType.remark = "";
        this.evalResult.colType.status = "";
      }
    },

    //审计进度admin是1表示审计有权限  user:1 说明是报告有权限
    getAdminAuth() {
      return this.progressData.admin === "1" ? true : false;
    },
    setStep() {
      let { reportOprDetails } = this.progressData;
      this.steps = [];
      //根据后台返回的数据，填充时间和操作人
      let newStatus = JSON.parse(JSON.stringify(this.$store.state.dictionary[100800]));
      newStatus.forEach((item, index) => {
        if (item.value) {
          let obj = { statusName: item.label, status: item.value, time: "", operaUser: "" };
          reportOprDetails.forEach((step) => {
            if (step.status == item.value) {
              obj.time = step.time;
              obj.operaUser = step.operaUser;
            }
          });
          this.steps.push(obj);
        }
        //走到了哪一步
        console.log("this.progressData.status", this.progressData.status);
        if (this.progressData.status == item.value) {
          this.active = this.progressData.status === "36" ? index + 1 : index;
        } else if (this.progressData.status === "37") {
          //已归档 审计进度到已完成步骤
          this.active = 6;
        } else if (this.progressData.status === "50") {
          //已归档 审计进度到已完成步骤
          this.active = -1;
        }
      });
    },
    //误报
    ignoreRefConfirm() {
      riskMisreportApi({ ids: [this.selectRisk.id], status: "121", remark: this.ignoreData.remark }).then((res) => {
        let state = this.message.state(res);
        if (!state) return;
        this.ignoreDiaShow = false;
        this.message.success({ message: res.msg });
        this.getRiskList();
        this.getReportItems(); //审计结果
        this.getReportDetail(); //审计进度数据获取
      });
    },
    /**
     * @函数功能:审计状态在信息补全和审计确认的时候 去校验审计结果和现状描述 如果审计结果是(待审计的)一定要选择成其他的审计结果 如果是不合适的，一定要填写现状描述
     * @参数输入:
     * @函数返回:
     */
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (!column) {
        return;
      }
      //审计结果阶段不能有待审计选择
      if (this.progressData.status === "13") {
        if (column.property === "status" && row.status === "100") {
          return "required";
        }
      }
      //不适用的置灰颜色值
      if (row.status === "-1") {
        return "disabledStyle";
      }
    },

    save(refresh) {
      this.saveOrSubmit("save", refresh);
    },
    saveOrSubmit(opera, refresh) {
      if (opera === "submit") {
        var loading = this.openLoading();
      }
      upmSaveOrSubmitApi({
        reportId: this.query.id,
        status: this.progressData.status,
        opera: opera, //save 保存 submit提交
        items: this.evalResult.rows,
      }).then((res) => {
        if (opera === "submit") {
          loading.close();
          this.initPage();
        } else if (opera === "save") {
          refresh && this.getReportItems();
          refresh && this.message.success({ message: res.msg }); //现状描述失去焦点的时候保存但是不需要提示
        }
      });
    },
    saveAndSubmit() {
      let sign = false;
      let rows = this.evalResult.rows;
      //在信息补全和审计确认的状态下 风险结果不能是待审计 如果审计结果是不符合，现状描述一定要填写
      rows.forEach((item) => {
        if (this.progressData.status === "12" || this.progressData.status === "13") {
          if (item.status !== "-1" && !item.remark) {
            sign = true;
          }
        } else if (this.progressData.status === "13") {
          if (item.status === "100") {
            sign = true;
          }
        }
      });
      if (sign) {
        this.message.warning({
          message: "有必填项未填写",
        });
        return;
      }
      this.saveOrSubmit("submit");
    },
    /**
     * @函数功能:同步漏洞平台 这个点击是同步所有的漏洞平台
     * @参数输入:
     * @函数返回:
     */
    setRiskSoc() {
      // this.holeDiaShow = true;
      this.utils.$confirm({ content: "是否确认同步漏洞并生成审计报告？" }, () => {
        this.selectRisk = {};
        this.asyncHoleConfirm();
      });
    },
    /**
     * @函数功能:同步漏洞平台 弹框的确认按钮
     * @参数输入:relationId:"" 是同步所有的漏洞平台并生成报告  riskIds:[] 这个是同步一个到漏洞平台
     * @函数返回:
     */
    asyncHoleConfirm() {
      let riskIds = this.selectRisk.id ? [this.selectRisk.id] : [];
      let relationId = this.selectRisk.id ? "" : this.query.id;
      riskSocApi({ relationId: relationId, riskIds: riskIds, dateType: "upm_report" }).then((res) => {
        // this.holeDiaShow = false;
        this.message.success({ message: res.msg });
        this.getRiskList();
        this.getReportDetail(); //审计进度数据获取
      });
    },
  },
  watch: {},
  destroyed() {},
};
</script>
<style lang="scss" scoped>
//@import url(); 引入公共css类
.base-info {
  line-height: 30px;
}
.btn-box {
  margin-bottom: 10px;
}
::v-deep .required.el-table__cell .el-input input {
  border-color: red;
}
::v-deep .required.el-table__cell .el-textarea textarea {
  border-color: red;
}
::v-deep .disabledStyle.el-table__cell {
  background: #e6e6e6;
}
.el-upload__tip {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
</style>
